package fido.torrentsite;


import fido.DefaultTorrentImpl;
import fido.FidoCommonUtils;
import org.mymediadb.api.mmdb.model.Movie;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;


public final class NorBits extends CookiedTorrentSite {


    protected String getRegex() {
        return "<tr>.?<td align=center style='padding: 0px'>.*?<td align=left><a href=\\\"(.*?)\\\"><b><span title='(.*?)'>.*?href=\\\"(.*?)\\\">.*?</tr>";
    }

    protected String getURL() {
        return "http://www.norbits.net/browse.php";
    }

    protected String getSearchURL() {
        return "http://norbits.net/browse.php?c19=1&c28=1&search={0}&sort=seeders&h=11&d=DESC";
    }

    protected boolean isLoggedIn(String loginPageUrl) {
        return !(loginPageUrl.contains("takelogin.php"));
    }

    protected String getTextEncoding() {
        return "ISO-8859-1";
    }

    protected List<CookieVariable> getCookieVariables() {
        List<CookieVariable> cookieVariables = new ArrayList<CookieVariable>();
        cookieVariables.add(new CookieVariable("uid", "user id"));
        cookieVariables.add(new CookieVariable("pass", "passkey"));
        return cookieVariables;
    }


    protected DefaultTorrentImpl getTorrentFromMatcherData(Matcher matcher, Movie movie) {
        DefaultTorrentImpl torrent;
        int torrentCounter = 0;

        while (matcher.find()) {
            torrentCounter++;
            try {
                torrent = new DefaultTorrentImpl();
                torrent.setDetailsPageUrl("http://www.norbits.net/" + matcher.group(1));

                torrent.setName(matcher.group(2));
                torrent.setTorrentUrl("http://www.norbits.net/" + matcher.group(3));
                //torrent.setSeeders(Integer.parseInt(matcher.group(6)));
                //torrent.setLeechers(Integer.parseInt(matcher.group(7)));
                torrent.setCookie(getCookieString());

                if (FidoCommonUtils.doesImdbIdExistsInTorrentDetails(torrent, movie.getImdbId())) { //checking the NFO file for norBits
                    LOG.debug("Found torrent IMDBId in details page");
                    return torrent;
                }

                LOG.debug("Found torrent:" + torrent.getName() + " but imdbID didn't match");

            } catch (IndexOutOfBoundsException e) {
                LOG.info(e.toString());
                return null;
            }

        }

        if (torrentCounter == 0) {
            LOG.debug("No torrents found at all, There were no results on the search page?");
        } else {
            LOG.debug("Found " + torrentCounter + " torrents matching search name - but not ImdbID");
        }

        return null;
    }

}
